package com.example.usharingtest.fragment;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.usharingtest.R;
import com.example.usharingtest.adapter.MainAdapter;
import com.example.usharingtest.adapter.postAdapter;
import com.example.usharingtest.model.Article;
import com.example.usharingtest.model.Image;
import com.example.usharingtest.service.ServiceUrl;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by X on 2017/9/3.
 */
public class TravelFragment extends Fragment {

    private MainAdapter homeadapter= null;
    private List<Article> list = new ArrayList<>();
    private PullToRefreshListView pullToRefreshListView;
    private  List<List<Image>> imagelsit;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initialdata(3);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.pulltorefreshlist, container, false);
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    public void initialdata(int type){
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        String url = ServiceUrl.getUrl(getActivity(), R.string.URL_HOMEPAGE_ACTIVITY);

        RequestParams parameters = new RequestParams();
        parameters.put("type",Integer.toString(type));
        System.out.println("URL="+url);
        asyncHttpClient.setTimeout(11000);   //设置链接超时，如果不设置，默认为10s

        asyncHttpClient.get(url,parameters, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String content) {
                Log.d("内容", content);
                Toast.makeText(getActivity(), "服务器连接成功", Toast.LENGTH_SHORT).show();
                JSONObject jsonObject = JSONObject.parseObject(content);
                boolean success = jsonObject.getBoolean("success");
                if (success) {
                    String strobj = jsonObject.getString("data");
                    Log.d("strobj", strobj);
                    //注意：json字符串的属性字段名称和activity.class中的属性字段名称需要保存一致

                    list = JSON.parseArray(strobj,Article.class);

                    imagelsit=new ArrayList<>();
                    //从得到的数据中将图片url组合成list
                    for (Article article: list) {
                        ArrayList<Image> itemList=new ArrayList<>();
                        if(article.getPhotopath() != null) {
                            String[] photopathlist = article.getPhotopath().split(";");
                            for (String s: photopathlist) {
                                itemList.add(new Image(getContext().getResources().getString(R.string.URL_SERVER)+s, 250, 250));
                            }
                            imagelsit.add(itemList);
                        }
                    }

                    //版本三
                    homeadapter = new MainAdapter(getActivity(),imagelsit,list);
                    pullToRefreshListView = (PullToRefreshListView) getView().findViewById(R.id.pull_refresh_list);
                    //设置属性上拉下拉都可用
                    pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
                    //设置回调函数
                    pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>(){
                        @Override
                        public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                           // homeadapter.addToTop();
                            Toast.makeText(getActivity(),"刷新成功",Toast.LENGTH_SHORT).show();
                            new FinishRefresh().execute();
                        }

                        @Override
                        public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                           // homeadapter.addToBottom();
                            new FinishRefresh().execute();
                        }
                    });

                    ListView listView = pullToRefreshListView.getRefreshableView();
                    listView.setAdapter(homeadapter);
                    initRefreshListView();
                }
            }
            @Override
            public void onFailure(Throwable error, String content) {
                System.out.println("连接失败");
                Toast.makeText(getActivity(), "服务器连接错误，" + content, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /*
    * 下拉上拉状态设置*/
    public void initRefreshListView(){
        String str = DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
        ILoadingLayout lables = pullToRefreshListView.getLoadingLayoutProxy(true,true);
        lables.setPullLabel("拉取刷新");
        lables.setRefreshingLabel("正在刷新");
        lables.setReleaseLabel("释放刷新");
        lables.setLastUpdatedLabel("上次刷新时间:"+str);

    }

    /*继承AsynTask关闭刷新*/
    private class FinishRefresh extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {

            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            pullToRefreshListView.onRefreshComplete();
            homeadapter.notifyDataSetChanged();
        }
    }
}